package servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;

import toolkit.Debug;
import xml.DataListParser;
import bean.PizzaBean;
import domain.entity.User;
import domain.value.Ingredient;
import form.Form;
import form.FormField;
import form.element.Checkbox;

public class PizzaServlet extends AbstractStepServlet
{
	private static final long serialVersionUID = 1L;
	
	private Form form;
	
	private List<PizzaBean> ingredients;
	
	private List<PizzaBean> pizzas;
	
	public PizzaServlet()
	{
		Debug.log("(" + id + ") PizzaServlet()");
	}
	
	@Override
	public void init() throws ServletException
	{
		super.init();
		
		pizzas = getPizzasFromXml();
		
		ingredients = getIngredientsFromXml();
		
		// Prepare custom pizza form
		form = new Form("custompizza");
		
		if(ingredients != null && ingredients.size() > 0)
		{
			for (PizzaBean item: ingredients)
			{
				String name = (String) item.get("name");
				String price = (String) item.get("price");
				
				Checkbox checkbox = new Checkbox(name);
				checkbox.setLabel(name + " (&euro; " + price + ")");
				form.addChild(checkbox);
			}
		}
	}
	
	@Override
	public void preDispatch()
	{
		super.preDispatch();
		
		form.clear();
	}
	
	@Override
	public void dispatchGet() throws ServletException, IOException
	{
		Debug.log("(" + id + ") PizzaServlet.dispatchGet()");
		
		request.setAttribute("pizzas", pizzas);
		
		User user = (User) session.getAttribute("user");
		
		Debug.log("user = " + user);
		
		if (user != null)
		{
			Debug.log("username = " + user.getName());
			
			request.setAttribute("name", user.getName());
		}
		
		session.setAttribute("pizza", null);
		
		display();
		
		resetStep();
	}
	
	@Override
	public void dispatchPost() throws ServletException, IOException
	{
		Debug.log("(" + id + ") PizzaServlet.dispatchPost()");
		
		String pizzaName = request.getParameter("selectedpizza");
		
		if (pizzaName != null)
		{
			PizzaBean selectedPizza = null;
			
			for (PizzaBean pizza: pizzas)
			{
				if (pizza.get("name").equals(pizzaName))
				{
					selectedPizza = pizza;
					
					break;
				}
			}
			
			if (selectedPizza != null)
			{
				session.setAttribute("pizza", selectedPizza);
				
				redirectNextStep();
			}
			else
			{
				dispatchGet();
			}
		}
		else
		{
			PizzaBean pizza = new PizzaBean();
			
			form.populate(getPostValues());
			
			pizza = buidCustomPizza(form);
			
			if (pizza != null)
			{
				session.setAttribute("pizza", pizza);
				
				redirectNextStep();
			}
			else
			{
				dispatchGet();
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<PizzaBean> getPizzasFromXml()
	{
		List<PizzaBean> pizzas = new ArrayList<PizzaBean>();
		
		List<Map<String, Object>> list = null;
		
		try
		{
			list = new DataListParser().getDataListFrom("http://localhost/pizzas.xml");
		}
		catch (Exception e)
		{
			// Debug.log(e);
			
			try
			{
				list = new DataListParser().getDataListFrom("http://grayen.gr.funpic.de/pizzas.xml");
			}
			catch (Exception e1)
			{
			//	Debug.log(e1);
			}
		}
		
		if (list == null)
		{
			Debug.log("NO PIZZAS FOUND!");
			
			return null;
		}
		
		for (Map<String, Object> item: list)
		{
			PizzaBean pizza = new PizzaBean();
			pizza.populate(item);
			
			ArrayList<Ingredient> ingredients = new ArrayList<Ingredient>();
			
			for (Map<String, Object> ingredientData: (List<Map<String, Object>>) pizza.get("ingredients"))
			{
				ingredients.add(new Ingredient((String) ingredientData.get("name")));
			}
			
			pizza.put("ingredients", ingredients);
			
			pizzas.add(pizza);
		}
		
		return pizzas;
	}
	
	public List<PizzaBean> getIngredientsFromXml()
	{
		List<PizzaBean> ingredients = new ArrayList<PizzaBean>();
		
		List<Map<String, Object>> list = null;
		
		try
		{
			list = new DataListParser().getDataListFrom("http://localhost/ingredients.xml");
		}
		catch (Exception e)
		{
			//Debug.log(e);
			
			try
			{
				list = new DataListParser().getDataListFrom("http://grayen.gr.funpic.de/ingredients.xml");
			}
			catch (Exception e1)
			{
				//Debug.log(e1);
			}
		}
		
		if (list == null)
		{
			Debug.log("NO INGREDIENTS FOUND!");
			
			return null;
		}
		
		for (Map<String, Object> item: list)
		{
			PizzaBean pizza = new PizzaBean();
			pizza.populate(item);
			ingredients.add(pizza);
		}
		
		return ingredients;
	}
	
	private PizzaBean buidCustomPizza(Form form)
	{
		PizzaBean pizza = new PizzaBean();
		
		double price = 0.0;
		
		ArrayList<Ingredient> ingredients = new ArrayList<Ingredient>();
		
		List<FormField> attributen = form.getFields();
		
		for (FormField item: attributen)
		{
			Checkbox box = (Checkbox) item;
			
			if (box.isChecked())
			{
				for (PizzaBean bean: this.ingredients)
				{
					if (bean.get("name").equals(box.getName()))
					{
						ingredients.add(new Ingredient(box.getName()));
						
						price += Double.parseDouble((String) bean.get("price"));
					}
				}
			}
		}
		
		if (ingredients.size() > 0)
		{
			pizza.put("ingredients", ingredients);
			pizza.put("name", "Aangepaste pizza");
			pizza.put("price", String.valueOf(price));
			
			return pizza;
		}
		
		return null;
	}
}
